<template>
  <div>
    <Header v-if="showHeader" title="我要申请"></Header>
    <div class="apply">
      <ul class="read_list">
        <li>
          <label>考核周期</label>
          <input type="text" :value="readList.cycle_name" readonly />
        </li>
        <li>
          <label>考核时间段</label>
          <input type="text" v-if="readList.begin_date && readList.end_date" :value="readList.begin_date +' 至 '+ readList.end_date" readonly />
        </li>
        <li>
          <label>考核得分(分)</label>
          <input type="text" :value="readList.score" readonly />
        </li>
        <li>
          <label>历史申请次数(次)</label>
          <input type="text" :value="readList.history_alpply_num" readonly />
        </li>
        <template v-if="readList.targets.length">
          <li v-for="(item,index) in readList.targets" :key="index">
            <label class="flex6">{{item.name}} 完成量/目标量 </label>
            <input class="flex1" type="text" :value="item.target_data+'/'+item.target_value" readonly />
          </li>
        </template>
        <!-- <li>
          <label>指标一完成量(个)</label>
          <input type="text" v-if="readList.targets.length" :value="readList.targets[0].target_data" readonly />
        </li>
        <li>
          <label>指标二完成量(个)</label>
          <input type="text" v-if="readList.targets.length>1" :value="readList.targets[1].target_data" readonly />
        </li> -->
      </ul>
      <div class="apply_content">
        <p>申请内容</p>
        <p>{{readList.apply_title}}</p>
      </div>
      <div class="apply_reason">
        <p>
          <i class="require_tip">*</i> 申请理由
        </p>
        <van-cell-group>
          <van-field
            type="textarea"
            rows="3"
            autosize
            v-model="applyReason"
            maxlength="1000"
            show-word-limit
            placeholder="请输入延期申请理由"
          />
        </van-cell-group>
      </div>
      <div class="upload_images">
        <p>
          图片上传
          <span>(限上传{{maxCount}}张图片)</span>
        </p>
        <van-uploader v-model="fileList" multiple :max-count="maxCount" deletable />
      </div>
      <div class="organization">
        <p class="title">单据所属组织</p>
        <div class="select_organization">
          <van-dropdown-menu direction="up" active-color="#02ccbd">
            <van-dropdown-item v-model="organize_index" :options="organizes" @change="selectValue" />
          </van-dropdown-menu>
        </div> 
      </div>
      <ApprovalStep :stepList="stepList" :activeStep="activeStep"></ApprovalStep>
      <van-tabbar :z-index="1000">
        <van-tabbar-item>
          <van-button
            native-type="button"
            size="large"
            @click="postApply"
            :disabled="disabled"
          >提交</van-button>
        </van-tabbar-item>
      </van-tabbar>
    </div>
    <Loading v-show="showLoading"></Loading>
    <van-overlay :show="show" :z-index="1001" />
  </div>
</template>
<script>
import axios from "axios";
import _ from "lodash";
import Loading from "@/components/Loading.vue";
import Header from "@/components/Header.vue";
import ApprovalStep from "@/components/business/ApprovalStep.vue";
import { applyListV3, postApplyV3, uploadImgs,checkLineV3} from "@/request/api.js";
export default {
  data() {
    return {
      show:false,
      maxCount:3,
      organizationList: "",
      showHeader: this.$store.state.showHeader,
      showLoading: true,
      readList: {
        cycle_name: "",
        begin_date: "",
        end_date: "",
        score: "",
        history_alpply_num:"",
        targets:[],
        apply_title:''
      },
      applyReason: "",
      stepList: [],
      activeStep: 0,
      staffer_id: "",
      fileList: [],
      imageList: [],
      organize_index:0,
      organizes: [],
      selectedObj:{
        job_id: "",
        organize_id: "",
        organize_job_name: "",
      },
      uploadFilequery: {}
    };
  },
  components: { ApprovalStep, Loading, Header },
  created() {
    this.staffer_id = localStorage.getItem("staffer_id");
    applyListV3({token: this.$store.state.token,staffer_id: this.staffer_id}).then(res => {
      this.showLoading = false;
      if (res.code) {
          this.$dialog.alert({
              title:'提示',
              message: res.msg
          }).then(() => {
              this.$router.go(-1)
          });
      } else {
        let data = res.data;
        this.readList.cycle_name = data.cycle_name;
        this.readList.begin_date = data.begin_date;
        this.readList.end_date = data.end_date;
        this.readList.history_alpply_num = data.history_alpply_num;
        this.readList.score = data.score;
        data.targets.length?this.readList.targets = data.targets:this.readList.targets = [];
        this.readList.apply_title = data.apply_title;
        this.selectedObj.organize_id = data.organic_id;
        this.selectedObj.job_id = data.job_id;
        if(data.organizes.length){
          this.organizes = data.organizes;
          for(let i = 0;i<this.organizes.length;i++){
            let cur = this.organizes[i];
            cur.text = cur.organize_job_name;
            cur.value = i;
            if(data.organic_id==cur.organize_id&&data.job_id==cur.job_id){
              this.organize_index=i;
              this.selectedObj={
                job_id: data.job_id,
                organize_id: data.organic_id,
                organize_job_name: "",
              }
            }
          }
        }
        //获取图片上传阿里云凭证
        this.getAliConfig();
        //审批流
        checkLineV3({
          token: this.$store.state.token, 
          staffer_id: this.staffer_id,
          organize_id:data.organic_id,
          job_id:data.job_id
        }).then(res=>{
          console.log(res)
          if(res.code){
            this.$toast({
              message:res.msg,
              duration:1200
            })
          }else{
            this.stepList = res.data.check_line;
          };
        }).catch(err=>{
          console.log(err)
        })
      };
    }).catch(error => {
      console.log(error);
      this.showLoading = false;
    });
  },
  computed:{
    disabled(){
      return this.applyReason.length<=0 || !this.applyReason
    }
  },
  methods: {
    isObjArr(value){
        if (Object.prototype.toString.call(value) === "[object Array]") {
                console.log('value是数组');
          }else if(Object.prototype.toString.call(value)==='[object Object]'){
                console.log('value是对象');
          }else{
              console.log('value不是数组也不是对象')
          }
    },
    //获取图片上传阿里云凭证
    getAliConfig(){
      uploadImgs({ 
          token: this.$store.state.token,
          project: "oa",
          project_key: "diangou"
        }).then(res => {
          console.log(res);
          this.uploadFilequery = res.data;
        }).catch(error => {
          console.log(error);
        });
    },
    //筛选组织
    selectValue(index){
      this.showLoading = true;
      this.organize_index = index;
      this.selectedObj = this.organizes[index];
      checkLineV3({
        token: this.$store.state.token, 
        staffer_id: this.staffer_id,
        organize_id:this.selectedObj.organize_id,
        job_id:this.selectedObj.job_id
      }).then(res=>{
        if(res.code){
          this.$toast({
            message:res.msg,
            duration:1200
          })
        }else{
          this.stepList = res.data.check_line;
        };
        this.showLoading = false;
      }).catch(err=>{
        console.log(err)
        this.showLoading = false;
      })
    },
    addApply(){
      postApplyV3({
        token: this.$store.state.token,
        staffer_id: this.staffer_id,
        remark: this.applyReason,
        images: this.imageList,
        organize_id:this.selectedObj.organize_id,
        job_id:this.selectedObj.job_id
      }).then(res => {
        console.log(res)
        this.showLoading = false;
        this.show = false;
        if (res.code == 0) {
          this.$toast({
            duration: 800,
            message: res.msg
          });
          const timer = setTimeout(() => {
            this.showLoading = false;
            this.$router.push({ path: "/sevenDelay" });
            clearTimeout(timer);
          }, 1000);
        } else {
          this.$toast({
            duration: 800,
            message: res.code + ":" + res.msg
          });
        }
      }).catch(error => {
        console.log(error.msg);
        this.showLoading = false;
        this.show = false;
      });
    },
    //提交
    postApply() {
      this.showLoading = true;
      this.show = true;
      let files = _.cloneDeep(this.fileList);
      if (files.length) {
        let num = 0;
        // const promises = files.map(file=>{
        //   let data = new FormData();
        //   let ext = file.file.name.substr(file.file.name.lastIndexOf(".")).toLowerCase(); //获得后缀
        //   let uploadFileName = this.uploadFilequery.dir + this.random_string() + ext;
        //   data.append("OSSAccessKeyId", this.uploadFilequery.accessid);
        //   data.append("policy", this.uploadFilequery.policy);
        //   data.append("Signature", this.uploadFilequery.signature);
        //   data.append("success_action_status", "200");
        //   data.append("key", uploadFileName);
        //   data.append("file", file.file);
        //   this.imageList.push(uploadFileName);
        //   return axios.post(this.uploadFilequery.host,data,{ headers:{ "Content-Type": "application/x-www-form-urlencoded" }});
        // });
        // Promise.all(promises).then( res =>{
        //   console.log('上传阿里云成功啦');
        //   this.addApply();
        // }).catch( error =>{
        //   console.log('上传阿里云失败啦');
        //   console.log(error);
        //   this.$toast({
        //     message:'当前网络不稳定，请重新提交单据',
        //     duration:2500
        //   })
          // //重新获取图片上传阿里云凭证
          // this.getAliConfig();
          // this.maxCount = 1;
          // this.fileList = [];
          // this.imageList = [];
          // this.showLoading = false;
        // });
        for (let i = 0; i < files.length; i++) {
          let data = new FormData();
          let file = files[i];
          let ext = file.file.name.substr(file.file.name.lastIndexOf(".")).toLowerCase(); //获得后缀
          let uploadFileName = this.uploadFilequery.dir + this.random_string() + ext;
          data.append("OSSAccessKeyId", this.uploadFilequery.accessid);
          data.append("policy", this.uploadFilequery.policy);
          data.append("Signature", this.uploadFilequery.signature);
          data.append("success_action_status", "200");
          data.append("key", uploadFileName);
          data.append("file", file.file);
          axios.post(this.uploadFilequery.host,data,{ headers:{ "Content-Type": "application/x-www-form-urlencoded" },timeout:35000}).then(res => {
            console.log('提交阿里云成功!');
            this.imageList.push(uploadFileName);
            num++;
            if(num==files.length){
              this.addApply();
            };
          }).catch(error => {
            console.log('上传阿里云失败啦');
            console.log(error);
            this.$toast({
              message:'当前网络不稳定，请重新提交单据',
              duration:2500
            })
            //重新获取图片上传阿里云凭证
            this.getAliConfig();
            this.maxCount = 1;
            this.fileList = [];
            this.imageList = [];
            this.showLoading = false;
            this.show = false;
          });
        };
      }else{
        // console.log('111')
        this.addApply();
      }
    },
    //随机字符串
    random_string(len) {
      len = len || 32;
      var chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
      var maxPos = chars.length;
      var pwd = "";
      var i = 0;
      for (; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return pwd;
    },
  }
};
</script>
<style lang="less" scoped>
/deep/ [class*=van-hairline]::after{border:none;}
/deep/ .van-overlay{
  background-color: rgba(0, 0, 0, 0);
}
.apply {
  padding-bottom: 100px;
  .read_list {
    width: 100%;
    height: auto;
    background: #fff;
    li {
      padding: 10px;
      line-height: 36px;
      border-bottom: 1px solid #f7f7f7;
      font-size: 14px;
      color: #999;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;
      label {
        flex: 1;
      }
      .flex6{flex: 6;}
      input {
        flex: 2;
        text-align: right;
        color: #151617;
        font-weight: bold;
      }
      .flex1{flex: none;width: 100px;}
    }
  }
  .apply_content,.organization {
    width: 100%;
    height: 40px;
    line-height: 40px;
    padding: 10px 15px;
    background: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    margin-top: 10px;
    border-bottom: 1px solid #f7f7f7;
    font-size: 14px;
  }
  .organization {
    height: auto;
    line-height: 30px;
    overflow: hidden;
    .select_organization{
      flex: 2;
    }
    .van-dropdown-menu{height: 40px;}
    /deep/ .van-dropdown-item__content .van-cell__title{flex: 4;}
    /deep/ .van-dropdown-menu__bar{height: 40px;background: none;box-shadow: none;}
    /deep/.van-dropdown-menu__item{justify-content: flex-end;}
    /deep/.van-ellipsis{
      font-size: 12px;
      white-space: normal;
      text-overflow: inherit;
    }
  }
  .apply_reason {
    border-bottom: 1px solid #f7f7f7;
  }
  .apply_reason,
  .upload_images {
    width: 100%;
    height: auto;
    background: #fff;
    padding: 10px 15px;
    box-sizing: border-box;
    color: #151617;
    font-size: 14px;
    p {
      line-height: 36px;
      font-weight: bold;
      .require_tip {
        color: red;
        vertical-align: middle;
        font-size: 14px;
      }
    }
    .van-hairline--top-bottom::after,
    .van-hairline-unset--top-bottom::after {
      border: none;
    }
    .van-cell {
      padding: 0;
      font-size: 14px;
      color: #999;
    }
  }
  .upload_images {
    span {
      color: #999;
      font-weight: normal;
    }
    /deep/ .van-uploader__upload {
      background: #f7f7f7;
      .van-uploader__upload-icon {
        font-size: 30px;
      }
    }
    // /deep/ .van-uploader__preview-delete {
    //   display: none;
    // }
  }
  /deep/ .van-tabbar-item__text {
    display: block;
    width: 100%;
  }
  /deep/ .van-button--large {
    font-size: 16px;
    font-weight: bold;
    background-color: #02ccbd;
    color: #fff;
  }
}
.content {
  width: 100%;
  height: 335px;
  background: #fff;
  overflow: hidden;
}
</style>